// --数据分组引发的思考【渡一教育】

const people = [
  {
    name: "John",
    age: 30,
    gender: "male",
    address: {
      street: "123 Main St",
      city: "Anytown",
      state: "CA",
      zip: "12345",
    },
  },
  {
    name: "Jane",
    age: 25,
    gender: "female",
    address: {
      street: "456 Oak St",
      city: "Othertown",
      state: "NY",
      zip: "67890",
    },
  },
  {
    name: "Jim",
    age: 40,
    gender: "male",
    address: {
      street: "789 Pine St",
      city: "Sometown",
      state: "TX",
      zip: "54321",
    },
  },
  {
    name: "Bob",
    age: 40,
    gender: "male",
    address: {
      street: "789 Pine St",
      city: "Sometown",
      state: "TX",
      zip: "54321",
    },
  },
  {
    name: "Alice",
    age: 35,
    gender: "female",
    address: {
      street: "321 Maple St",
      city: "Uptown",
      state: "FL",
      zip: "09876",
    },
  },
  {
    name: "Charlie",
    age: 45,
    gender: "male",
    address: {
      street: "654 Elm St",
      city: "Villagetown",
      state: "IL",
      zip: "13579",
    },
  },
];

// 根据指定的键将数组中的元素分组
function groupBy(arr, generateKey) {
  // 参数归一化
  if (typeof generateKey === "string") {
    const propName = generateKey;
    generateKey = (item) => item[propName];
  }
  const result = {};
  arr.forEach((item, i) => {
    const key = generateKey(item, i, arr);
    if (!result[key]) {
      result[key] = [];
    }
    result[key].push(item);
  });
  return result;
}

const result = groupBy(people, (p) => p.gender);
console.log(result);

const result3 = groupBy(people, "gender");
console.log("result3", result3);

const result1 = groupBy(people, (p) => `${p.gender}-${p.age}`);
console.log(result1);

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result2 = groupBy(numbers, (n) => (n % 2 === 0 ? "even" : "odd"));
console.log(result2);
